/**
 * 
 */
package net.plankton.converter;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hacklm
 *
 */
public abstract class DirectoryWatcher extends Thread {

	public DirectoryWatcher(String rootDir) {
		this.rootDir=rootDir;
	}
	
	String rootDir;
	List<String> convertedFiles = new ArrayList<String>();
	Map<String, Long> watchedFiles = new HashMap<String, Long>();
	
	
	@Override
	public void run() {
		while (true) {
			File dir = new File (rootDir);
			if (!dir.exists() || !dir.isDirectory()) {
				System.err.println("directory does not exist: "+rootDir);
				break;
			}
			File[] files = dir.listFiles();
			for (int i=0;i<files.length;i++) {
				if (!convertedFiles.contains(files[i].getAbsolutePath())) {
					if (watchedFiles.containsKey(files[i].getAbsolutePath())) {
						System.err.println(files[i].getAbsolutePath());
						long oldSize = watchedFiles.get(files[i].getAbsolutePath());
						long newSize = files[i].length();
						if (oldSize== newSize) {
							convertedFiles.add(files[i].getAbsolutePath());
							watchedFiles.remove(files[i].getAbsolutePath());
							handle(files[i]);
						}
						else {
							watchedFiles.put(files[i].getAbsolutePath(), newSize);
						}
					}
					else {
						watchedFiles.put(files[i].getAbsolutePath(), files[i].length());
					}
				}
				
			}
			try {
				Thread.sleep(5000);
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public abstract void handle(File f);
	
}
